﻿using BluetoothMachine.GlobalStatics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using BluetoothMachine.Entity;
using System.ComponentModel;
using Prism.Commands;
using System.Windows.Controls;
using BluetoothMachine.ExpandHelper;
using BluetoothMachine.Lucifer;
using BluetoothMachine.Protocols;
using System.Diagnostics;
using System.Threading;
using BluetoothMachine.Models;
using BluetoothMachine.Domains;

namespace BluetoothMachine.ViewModels
{
    public class InfraredLearningViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// 输出日志
        /// </summary>
        public string LogMessage { get; set; }
        public ObservableCollection<InfraredData> InfraredList { get; set; }
        public AsyncObservableCollection<InfraredLogModel> InfraredLog { get; set; }
        private ParameterConfigurationGlobal _parameter { get; set; }
        private DeviceManagementGlobal _device;
        public ObservableCollection<string> KeyNameList { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;
        public string KeyName { get; set; }

        public InfraredLearningViewModel(DeviceManagementGlobal device, ParameterConfigurationGlobal parameter)
        {
            _parameter = parameter;
            _device = device;
            KeyNameList = new ObservableCollection<string>();
            InfraredLog = new AsyncObservableCollection<InfraredLogModel>();
            InfraredList = new ObservableCollection<InfraredData>();
        }

        /// <summary>
        /// 单步运行
        /// </summary>
        public DelegateCommand<Button> SingleStep => new DelegateCommand<Button>(async sender => {
            sender.IsEnabled = false;
            await Task.Run(() =>
            {
                var model = ProductionPoint.Find(ProductionPoint._.Aisle == 0 & ProductionPoint._.ProductModel == _parameter.ParameterModel.ProductModel & ProductionPoint._.KeyName == KeyName);
                if (model == null) return;
                MotorMovements.HomeMove(0, 2);
                MotorMovements.XYMove(0, new ushort[] { 0, 1 }, new double[] { model.Ppx, model.Ppy });
                if (model.Ppz != 0) MotorMovements.ShaftOperation(0, 2, (int)(model.Ppz / 0.005));
            });
            sender.IsEnabled = true;
        });

        public DelegateCommand<Button> UpdateKeyName => new DelegateCommand<Button>(async sender =>
        {
            sender.IsEnabled = false;
            KeyNameList.Clear();
            var list = await Task.Run(() => RemoteControlCoordinates.FindAll(RemoteControlCoordinates._.Aisle == 0 & RemoteControlCoordinates._.ProductModel == _parameter.ParameterModel.ProductModel));
            foreach (var item in list)
            {
                KeyNameList.Add(item.KeyName);
            }
            sender.IsEnabled = true;
        });

        /// <summary>
        /// 按键打击
        /// </summary>
        public DelegateCommand<Button> Keystroke => new DelegateCommand<Button>(async sender =>
        {
            sender.IsEnabled = false;
            string keyname = sender.Content.ToString();
            await Task.Run(() =>
            {
                try
                {
                    ICommunication eio = _device.ConnectList.FirstOrDefault(x => x.Index == 1 & x.CommType);
                    eio.Write(new byte[] { 0x68, 0x11, 0x11, 0x11, 0x16, 0x0D, 0x0A });
                    _ = eio.Read();
                    switch (keyname)
                    {
                        case "红外按键":
                            eio.Write(new byte[] { 0x68, 0x22, 0x22, 0x22, 0x16, 0x0D, 0x0A });
                            break;
                        case "载波精度":
                            eio.Write(new byte[] { 0x68, 0x44, 0x44, 0x44, 0x16, 0x0D, 0x0A });
                            break;
                        case "红外强度":
                            eio.Write(new byte[] { 0x68, 0x55, 0x55, 0x55, 0x16, 0x0D, 0x0A });
                            break;
                        default:
                            break;
                    }
                    _ = eio.Read();
                    Stopwatch stopwatch = new Stopwatch();
                    LTDMC.dmc_write_outbit(0, 1, 0);
                    LTDMC.dmc_write_outbit(0, 3, 0);
                    stopwatch.Restart();
                    while (stopwatch.ElapsedMilliseconds < _parameter.ParameterModel.TimeKey)
                    {
                        Thread.Sleep(5);
                    }
                    LTDMC.dmc_write_outbit(0, 1, 1);
                    LTDMC.dmc_write_outbit(0, 3, 1);
                    var bytes = eio.Read();
                    if (keyname == "红外按键")
                    {
                        InfraredLog.Insert(0, new InfraredLogModel()
                        {
                            RawData = BitConverter.ToString(bytes),
                            JudgmentData = BitConverter.ToString(bytes.Skip(4).Take(2).ToArray())
                        });
                    }
                    LogMessage += $"{DateTime.Now:T} {BitConverter.ToString(bytes)}\r\n";
                    eio.Write(new byte[] { 0x68, 0x33, 0x33, 0x33, 0x16, 0x0D, 0x0A });
                    _ = eio.Read();
                }
                catch (Exception ex)
                {
                    LogMessage = ex.Message;
                }
            });
            sender.IsEnabled = true;
        });
    }
}
